# -*- coding: utf-8 -*-
"""
数据库连接界面
"""
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QGridLayout,
                            QLabel, QLineEdit, QPushButton, QComboBox, QCheckBox,
                            QGroupBox, QListWidget, QMessageBox, QInputDialog,
                            QListWidgetItem, QSplitter)
from PyQt5.QtCore import Qt, pyqtSignal, QThread
from PyQt5.QtGui import QFont, QIcon
from database.mysql_connector import MySQLConnector
from database.models import DatabaseManager
from utils.simple_encryption import encryption_manager

class ConnectionTestThread(QThread):
    """连接测试线程"""
    test_finished = pyqtSignal(bool, str)
    
    def __init__(self, mysql_connector, host, port, database, username, password):
        super().__init__()
        self.mysql_connector = mysql_connector
        self.host = host
        self.port = port
        self.database = database
        self.username = username
        self.password = password
    
    def run(self):
        """执行连接测试"""
        success, message = self.mysql_connector.test_connection(
            self.host, self.port, self.database, self.username, self.password
        )
        self.test_finished.emit(success, message)

class ConnectionWidget(QWidget):
    """数据库连接界面"""
    
    connection_changed = pyqtSignal(bool)
    
    def __init__(self, mysql_connector: MySQLConnector):
        super().__init__()
        self.mysql_connector = mysql_connector
        self.db_manager = DatabaseManager()
        self.encryption_manager = encryption_manager
        self.test_thread = None
        
        self.init_ui()
        self.load_saved_connections()
    
    def init_ui(self):
        """初始化界面"""
        layout = QVBoxLayout(self)
        
        # 创建分割器
        splitter = QSplitter(Qt.Horizontal)
        layout.addWidget(splitter)
        
        # 左侧：连接配置
        self.create_connection_config(splitter)
        
        # 右侧：已保存的连接
        self.create_saved_connections(splitter)
        
        # 设置分割器比例
        splitter.setSizes([400, 300])
    
    def create_connection_config(self, parent):
        """创建连接配置区域"""
        config_widget = QWidget()
        config_layout = QVBoxLayout(config_widget)
        
        # 连接配置组
        config_group = QGroupBox("数据库连接配置")
        config_group_layout = QGridLayout(config_group)
        
        # 主机地址
        config_group_layout.addWidget(QLabel("主机地址:"), 0, 0)
        self.host_edit = QLineEdit()
        self.host_edit.setText("localhost")
        self.host_edit.setPlaceholderText("例如: localhost 或 192.168.1.100")
        config_group_layout.addWidget(self.host_edit, 0, 1)
        
        # 端口号
        config_group_layout.addWidget(QLabel("端口号:"), 1, 0)
        self.port_edit = QLineEdit()
        self.port_edit.setText("3306")
        self.port_edit.setPlaceholderText("默认: 3306")
        config_group_layout.addWidget(self.port_edit, 1, 1)
        
        # 数据库名
        config_group_layout.addWidget(QLabel("数据库名:"), 2, 0)
        self.database_edit = QLineEdit()
        self.database_edit.setPlaceholderText("请输入数据库名称")
        config_group_layout.addWidget(self.database_edit, 2, 1)
        
        # 用户名
        config_group_layout.addWidget(QLabel("用户名:"), 3, 0)
        self.username_edit = QLineEdit()
        self.username_edit.setPlaceholderText("请输入用户名")
        config_group_layout.addWidget(self.username_edit, 3, 1)
        
        # 密码
        config_group_layout.addWidget(QLabel("密码:"), 4, 0)
        self.password_edit = QLineEdit()
        self.password_edit.setEchoMode(QLineEdit.Password)
        self.password_edit.setPlaceholderText("请输入密码")
        config_group_layout.addWidget(self.password_edit, 4, 1)
        
        # 保存密码选项
        self.save_password_checkbox = QCheckBox("保存密码")
        config_group_layout.addWidget(self.save_password_checkbox, 5, 1)
        
        config_layout.addWidget(config_group)
        
        # 连接按钮
        button_layout = QHBoxLayout()
        
        self.test_button = QPushButton("测试连接")
        self.test_button.clicked.connect(self.test_connection)
        button_layout.addWidget(self.test_button)
        
        self.connect_button = QPushButton("连接")
        self.connect_button.clicked.connect(self.connect_database)
        self.connect_button.setStyleSheet("QPushButton { background-color: #4CAF50; color: white; font-weight: bold; }")
        button_layout.addWidget(self.connect_button)
        
        self.disconnect_button = QPushButton("断开连接")
        self.disconnect_button.clicked.connect(self.disconnect_database)
        self.disconnect_button.setEnabled(False)
        button_layout.addWidget(self.disconnect_button)
        
        config_layout.addLayout(button_layout)
        
        # 保存配置按钮
        save_layout = QHBoxLayout()
        
        self.save_config_button = QPushButton("保存配置")
        self.save_config_button.clicked.connect(self.save_connection_config)
        self.save_config_button.setEnabled(False)
        save_layout.addWidget(self.save_config_button)
        
        config_layout.addLayout(save_layout)
        
        config_layout.addStretch()
        parent.addWidget(config_widget)
    
    def create_saved_connections(self, parent):
        """创建已保存连接区域"""
        saved_widget = QWidget()
        saved_layout = QVBoxLayout(saved_widget)
        
        # 已保存连接组
        saved_group = QGroupBox("已保存的连接")
        saved_group_layout = QVBoxLayout(saved_group)
        
        # 连接列表
        self.connection_list = QListWidget()
        self.connection_list.itemDoubleClicked.connect(self.load_saved_connection)
        saved_group_layout.addWidget(self.connection_list)
        
        # 操作按钮
        button_layout = QHBoxLayout()
        
        self.load_button = QPushButton("加载")
        self.load_button.clicked.connect(self.load_saved_connection)
        button_layout.addWidget(self.load_button)
        
        self.delete_button = QPushButton("删除")
        self.delete_button.clicked.connect(self.delete_saved_connection)
        button_layout.addWidget(self.delete_button)
        
        saved_group_layout.addLayout(button_layout)
        
        saved_layout.addWidget(saved_group)
        parent.addWidget(saved_widget)
    
    def test_connection(self):
        """测试连接"""
        if not self.validate_inputs():
            return
        
        # 禁用测试按钮
        self.test_button.setEnabled(False)
        self.test_button.setText("测试中...")
        
        # 创建测试线程
        self.test_thread = ConnectionTestThread(
            self.mysql_connector,
            self.host_edit.text().strip(),
            int(self.port_edit.text()),
            self.database_edit.text().strip(),
            self.username_edit.text().strip(),
            self.password_edit.text()
        )
        
        self.test_thread.test_finished.connect(self.on_test_finished)
        self.test_thread.start()
    
    def on_test_finished(self, success: bool, message: str):
        """测试完成"""
        self.test_button.setEnabled(True)
        self.test_button.setText("测试连接")
        
        if success:
            QMessageBox.information(self, "连接测试", "连接测试成功！")
        else:
            QMessageBox.warning(self, "连接测试", f"连接测试失败:\n{message}")
    
    def connect_database(self):
        """连接数据库"""
        if not self.validate_inputs():
            return
        
        # 禁用连接按钮
        self.connect_button.setEnabled(False)
        self.connect_button.setText("连接中...")
        
        # 执行连接
        success, message = self.mysql_connector.connect(
            self.host_edit.text().strip(),
            int(self.port_edit.text()),
            self.database_edit.text().strip(),
            self.username_edit.text().strip(),
            self.password_edit.text()
        )
        
        if success:
            QMessageBox.information(self, "连接成功", "数据库连接成功！")
            self.update_connection_ui(True)
            self.connection_changed.emit(True)
        else:
            QMessageBox.critical(self, "连接失败", f"数据库连接失败:\n{message}")
            self.connect_button.setEnabled(True)
            self.connect_button.setText("连接")
    
    def disconnect_database(self):
        """断开数据库连接"""
        self.mysql_connector.disconnect()
        self.update_connection_ui(False)
        self.connection_changed.emit(False)
        QMessageBox.information(self, "断开连接", "数据库连接已断开")
    
    def save_connection_config(self):
        """保存连接配置"""
        if not self.validate_inputs():
            return
        
        # 获取配置名称
        config_name, ok = QInputDialog.getText(
            self, "保存配置", "请输入配置名称:",
            text=f"{self.host_edit.text()}_{self.database_edit.text()}"
        )
        
        if not ok or not config_name.strip():
            return
        
        try:
            # 加密密码
            encrypted_password = self.encryption_manager.encrypt_password(self.password_edit.text())
            if not encrypted_password:
                QMessageBox.critical(self, "保存失败", "密码加密失败")
                return
            
            # 保存配置
            success = self.db_manager.save_db_connection(
                config_name.strip(),
                self.host_edit.text().strip(),
                int(self.port_edit.text()),
                self.database_edit.text().strip(),
                self.username_edit.text().strip(),
                encrypted_password
            )
            
            if success:
                QMessageBox.information(self, "保存成功", "连接配置已保存")
                self.load_saved_connections()
            else:
                QMessageBox.critical(self, "保存失败", "保存连接配置失败")
                
        except Exception as e:
            QMessageBox.critical(self, "保存失败", f"保存连接配置时发生错误:\n{str(e)}")
    
    def load_saved_connection(self):
        """加载已保存的连接"""
        current_item = self.connection_list.currentItem()
        if not current_item:
            return
        
        connection_id = current_item.data(Qt.UserRole)
        if not connection_id:
            return
        
        try:
            # 获取连接配置
            config = self.db_manager.get_db_connection(connection_id)
            if not config:
                QMessageBox.critical(self, "加载失败", "连接配置不存在")
                return
            
            # 填充表单
            self.host_edit.setText(config['host'])
            self.port_edit.setText(str(config['port']))
            self.database_edit.setText(config['database_name'])
            self.username_edit.setText(config['username'])
            
            # 解密密码
            password = self.encryption_manager.decrypt_password(config['encrypted_password'])
            if password:
                self.password_edit.setText(password)
            else:
                QMessageBox.warning(self, "密码解密失败", "无法解密保存的密码，请重新输入")
                
        except Exception as e:
            QMessageBox.critical(self, "加载失败", f"加载连接配置时发生错误:\n{str(e)}")
    
    def delete_saved_connection(self):
        """删除已保存的连接"""
        current_item = self.connection_list.currentItem()
        if not current_item:
            QMessageBox.warning(self, "删除失败", "请选择要删除的连接配置")
            return
        
        connection_id = current_item.data(Qt.UserRole)
        connection_name = current_item.text()
        
        reply = QMessageBox.question(
            self, "确认删除", 
            f"确定要删除连接配置 '{connection_name}' 吗？",
            QMessageBox.Yes | QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            try:
                success = self.db_manager.delete_db_connection(connection_id)
                if success:
                    QMessageBox.information(self, "删除成功", "连接配置已删除")
                    self.load_saved_connections()
                else:
                    QMessageBox.critical(self, "删除失败", "删除连接配置失败")
            except Exception as e:
                QMessageBox.critical(self, "删除失败", f"删除连接配置时发生错误:\n{str(e)}")
    
    def load_saved_connections(self):
        """加载已保存的连接列表"""
        try:
            self.connection_list.clear()
            connections = self.db_manager.get_db_connections()
            
            for conn in connections:
                item = QListWidgetItem()
                item.setText(f"{conn['name']} ({conn['host']}:{conn['port']}/{conn['database_name']})")
                item.setData(Qt.UserRole, conn['id'])
                self.connection_list.addItem(item)
                
        except Exception as e:
            print(f"加载已保存连接失败: {e}")
    
    def validate_inputs(self) -> bool:
        """验证输入"""
        if not self.host_edit.text().strip():
            QMessageBox.warning(self, "输入错误", "请输入主机地址")
            self.host_edit.setFocus()
            return False
        
        try:
            port = int(self.port_edit.text())
            if port < 1 or port > 65535:
                raise ValueError()
        except ValueError:
            QMessageBox.warning(self, "输入错误", "端口号必须是1-65535之间的整数")
            self.port_edit.setFocus()
            return False
        
        if not self.database_edit.text().strip():
            QMessageBox.warning(self, "输入错误", "请输入数据库名称")
            self.database_edit.setFocus()
            return False
        
        if not self.username_edit.text().strip():
            QMessageBox.warning(self, "输入错误", "请输入用户名")
            self.username_edit.setFocus()
            return False
        
        if not self.password_edit.text():
            QMessageBox.warning(self, "输入错误", "请输入密码")
            self.password_edit.setFocus()
            return False
        
        return True
    
    def update_connection_ui(self, connected: bool):
        """更新连接界面状态"""
        self.connect_button.setEnabled(not connected)
        self.connect_button.setText("连接")
        self.disconnect_button.setEnabled(connected)
        self.save_config_button.setEnabled(connected)
        
        # 禁用/启用输入框
        widgets = [self.host_edit, self.port_edit, self.database_edit, 
                  self.username_edit, self.password_edit, self.test_button]
        for widget in widgets:
            widget.setEnabled(not connected)
